package com.market.fleamarket.repository;

import com.market.fleamarket.entity.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;

public interface ProductRepository extends JpaRepository<Product, Long> {
    // 可扩展自定义查询
    Page<Product> findByCategory_Id(Long categoryId, Pageable pageable);
    Page<Product> findByNameContaining(String keyword, Pageable pageable);
    Page<Product> findByStatusAndValidUntilAfter(String status, java.time.LocalDateTime now, Pageable pageable);

    // 增加支持多状态查询的方法
    Page<Product> findByStatusIn(List<String> statuses, Pageable pageable);

    // 复杂查询：查找在指定状态列表中且有效期未过期或无有效期的商品
    @Query("SELECT p FROM Product p WHERE p.status IN :statuses AND (p.validUntil IS NULL OR p.validUntil > :now)")
    Page<Product> findByStatusInAndValidUntilAfterOrValidUntilIsNull(
            @Param("statuses") List<String> statuses,
            @Param("now") LocalDateTime now,
            Pageable pageable);

    // 根据用户ID查询该用户的所有商品
    Page<Product> findByUser_Id(Long userId, Pageable pageable);

    // 排除已删除商品的查询方法
    List<Product> findByStatusNot(String status);
    Page<Product> findByStatusNot(String status, Pageable pageable);
    Page<Product> findByCategory_IdAndStatusNot(Long categoryId, String status, Pageable pageable);
    Page<Product> findByNameContainingAndStatusNot(String keyword, String status, Pageable pageable);
    Page<Product> findByUser_IdAndStatusNot(Long userId, String status, Pageable pageable);

    // 复杂查询：查找在指定状态列表中且不是指定状态且有效期未过期或无有效期的商品
    @Query("SELECT p FROM Product p WHERE p.status IN :statuses AND p.status != :excludeStatus AND (p.validUntil IS NULL OR p.validUntil > :now)")
    Page<Product> findByStatusInAndStatusNotAndValidUntilAfterOrValidUntilIsNull(
            @Param("statuses") List<String> statuses,
            @Param("excludeStatus") String excludeStatus,
            @Param("now") LocalDateTime now,
            Pageable pageable);
} 